import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { GoodsCart } from '@/service/goods/cart/cart.d'

export const useActiveCartStore = defineStore(
  'activeCart',
  () => {
    const temporaryCart = ref<GoodsCart>({})
    const cartItems = ref<GoodsCart[]>([])
    const addCartItem = (item: GoodsCart) => {
      cartItems.value.push(item)
    }
    const removeCartItem = (id: number) => {
      cartItems.value = cartItems.value.filter((item) => item.id !== id)
    }
    const removeCartItemIds = (ids: number[]) => {
      if (!ids || !cartItems.value) return
      const idSet = new Set(ids)
      cartItems.value = cartItems.value.filter((item) => !idSet.has(item.id))
    }

    const clearCart = () => {
      cartItems.value = []
    }
    const setCart = (list: GoodsCart[]) => {
      cartItems.value = list
    }
    const selectedCount = computed(() => {
      return cartItems.value.filter((item) => item.selected === 1).length
    })

    const setTemporaryCart = (data: GoodsCart) => {
      temporaryCart.value = data
    }
    const clearTemporaryCart = () => {
      temporaryCart.value = {}
    }
    return {
      cartItems,
      selectedCount,
      addCartItem,
      removeCartItem,
      clearCart,
      setCart,
      removeCartItemIds,
      temporaryCart,
      setTemporaryCart,
      clearTemporaryCart,
    }
  },
  {
    persist: true,
  },
)
